package com.channel.temperature.collect.ui.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.inuker.bluetooth.library.Constants
import com.channel.temperature.collect.app.ble.BLECommand
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.ClientManager
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.base.BaseViewModel
import me.hgj.mvvmhelper.util.XLog
import java.text.DecimalFormat
import java.util.UUID


class BLEModel : BaseViewModel() {
    val baudsList = mutableListOf<String>(
        "9600", "14400", "19200", "38400", "57600", "115200", "230400", "460800", "921600"
    )
    val baudsValueList = mutableListOf<Byte>(
        0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
    )

    //锁具UUID
    val RX_SERVICE_UUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
    val RX_CHAR_UUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e") //写数据，从手机的角度

    val TX_CHAR_UUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e") //读数据

    var tipslistData = MutableLiveData<ArrayList<String>>()

    var isConnected = false
    var clickType = -1//1:查询SPP蓝牙地址 2：查询BLE蓝牙地址 3:设置HC-04的波特率
    var sendValue1 = 0
    var sendValue2 = 0

    var continueSendTCON = MutableLiveData<Boolean>()
    fun addMessage(msg: String) {
        viewModelScope.launch {
            var tempList = tipslistData.value
            if (tempList == null) {
                tempList = ArrayList<String>()
            }
            tempList.add(msg)
            tipslistData.value = tempList!!
        }
    }

    fun clearTips() {
        tipslistData.value = ArrayList<String>()
    }

    fun sendSleepTimeCMD(mMac: String, sleepTime: Int) {
        viewModelScope.launch {
            var cmd = BLECommand.setSleepTimeCmd(sleepTime)
            addMessage("命令发送... " + MyUtil.bytes2Hex(cmd))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, cmd
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }

        }
    }

    fun sendSerialPortCMD(mMac: String, value: Int) {
        viewModelScope.launch {
            var cmd = BLECommand.setSerialPortCmd(value)
            addMessage("命令发送... " + MyUtil.bytes2Hex(cmd))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, cmd
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }

        }
    }

    fun sendQueryDeviceInfoCMD(mMac: String) {
        viewModelScope.launch {
            var cmd = BLECommand.setQueryDeviceInfoCMD()
            addMessage("命令发送... " + MyUtil.bytes2Hex(cmd))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, cmd
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }

        }
    }

    fun sendCheckCMD(mMac: String, value1: Int, value2: Int) {
        viewModelScope.launch {
            var bufData = BLECommand.setCheckCmd(value1, value2)
            addMessage("命令发送... " + MyUtil.bytes2Hex(bufData))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, bufData
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }
        }
    }

    fun sendBaudCMD(mMac: String, baudValue: Int) {
        viewModelScope.launch {
            var bufData = BLECommand.setBaudCmd(baudValue)
            addMessage("命令发送... " + MyUtil.bytes2Hex(bufData))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, bufData
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }
        }
    }

    fun sendVOUTCMD(mMac: String, enValue: Boolean, open9700Value: Boolean) {
        viewModelScope.launch {
            Log.e(
                "sendVOUTCMD", "VOUT的输出值    " + mmkv.getBoolean(
                    ValueKey.enValue, false
                ) + "    " + mmkv.getBoolean(ValueKey.open9700Value, false)
            )
            var bufData = BLECommand.setVOUTCmd(
                enValue,
                open9700Value
            )
            XLog.e("得到的buf " + MyUtil.bytes2Hex(bufData))
            addMessage("命令发送... " + MyUtil.bytes2Hex(bufData))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, bufData
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }
        }
    }

    fun sendQueryElectCMD(mMac: String) {
        viewModelScope.launch {
            var bufData = BLECommand.setQueryElectCmd()
            XLog.e("得到的buf " + MyUtil.bytes2Hex(bufData))
            addMessage("命令发送... " + MyUtil.bytes2Hex(bufData))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, bufData
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }
        }
    }

    fun sendShortTCCmd(mMac: String, value: String) {
        viewModelScope.launch {
            var bufData = MyUtil.hex2Bytes(MyUtil.stringToAscii(value) + "0D0A")
            XLog.e("得到的buf " + MyUtil.bytes2Hex(bufData))
            addMessage("命令发送... " + MyUtil.bytes2Hex(bufData))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, bufData
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }
        }
    }

    fun sendShortTCCmd(mMac: String, value: String, withODOA: Boolean) {
        viewModelScope.launch {
            var bufData = if (withODOA) MyUtil.hex2Bytes(MyUtil.stringToAscii(value) + "0D0A")
            else MyUtil.hex2Bytes(MyUtil.stringToAscii(value))

            XLog.e("得到的buf " + MyUtil.bytes2Hex(bufData))
            addMessage("命令发送... " + MyUtil.bytes2Hex(bufData))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, bufData
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }
        }
    }

    fun send0D0A(mMac: String) {
        viewModelScope.launch {
            var bufData = MyUtil.hex2Bytes("0D0A")

            XLog.e("得到的buf " + MyUtil.bytes2Hex(bufData))
            addMessage("命令发送... " + MyUtil.bytes2Hex(bufData))
            ClientManager.getClient().write(
                mMac, RX_SERVICE_UUID, RX_CHAR_UUID, bufData
            ) { code ->
                if (code == Constants.REQUEST_SUCCESS) {
                    addMessage("发送指令成功")
                } else {
                    addMessage("发送指令失败")
                }
            }
        }
    }

    fun packageData(data: String): List<String> {
        var listdata = ArrayList<String>()
        var length = if (data.length % 20 == 0) {
            data.length / 20
        } else (data.length / 20) + 1
        for (i in 0..(length - 1)) {
            if (i == length - 1) {
                listdata.add(data.substring(i * 20, data.length))
            } else {
                listdata.add(data.substring(i * 20, (i + 1) * 20))
            }
        }
        return listdata
    }

    fun handleBLEResult(data: ByteArray) {
        when (data[3].toInt()) {
            0x11 -> {
                if (data[4].toInt() == 1) {
                    addMessage("设置休眠时间操作成功")
                }
            }

            0x12 -> {
                if (data[4].toInt() == 1) {

                    if (clickType == 4) {
                        viewModelScope.launch {
                            addMessage("设置控制通道波特率成功")
                            delay(30)
                            continueSendTCON.value = true

                        }

                    } else {
                        addMessage("设置控制通道波特率成功")
                    }

                }
            }

            0x13 -> {
                if (data[4].toInt() == 1) {
                    addMessage("设备电源控制成功")
                }
            }

            0x15 -> {
                var baudValueResult = "9600"
                for (i in 0 until baudsValueList.size) {
                    if (data[7] == baudsValueList[i]) {
                        baudValueResult = baudsList[i]
                    }
                }
                var dataString = MyUtil.bytes2Hex(data)
                addMessage(
                    "查询设备信息成功,厂家编号：" + dataString.substring(
                        8,
                        10
                    ) + " ,软件版本：" + dataString.substring(
                        10,
                        12
                    ) + " ,硬件版本：" + dataString.substring(
                        12,
                        14
                    ) + " ,串口波特率 ：" + baudValueResult + " , 串口地址 ：" +
                            dataString.substring(16, 18)
                )
            }

            0x16 -> {
                if (data[4].toInt() == 1) {
                    addMessage("校验命令成功")
                }
            }

            0x17 -> {
                if (data[4].toInt() == 1) {
                    addMessage("设置串口接收成功")
                }
            }

            0x14 -> {
//                if (data[4].toInt() == 11) {
                addMessage("查询输出电流/电压成功 : ")
                var maValue = MyUtil.bytes2Hex(data).substring(8, 16)
                var mVValue = MyUtil.bytes2Hex(data).substring(16, 20)
                var powerValue = MyUtil.bytes2Hex(data).substring(20, 24)
                var maValueRsult = ""
                if (maValue.toInt(16) == 0) {
                    maValueRsult = "0"
                } else {
                    maValueRsult = DecimalFormat("#.0000").format(
                        (maValue.toInt(16).toFloat() / 10000.0)
                    ).toFloat().toString()
                    if (maValueRsult.split(".")[1].length == 3) {
                        maValueRsult += "0"
                    }
                }

                var mVValueResult = ""

                if (mVValue.toInt(16) == 0) {
                    mVValueResult = "0"
                } else {
                    mVValueResult = DecimalFormat("#.000").format(
                        mVValue.toInt(16).toFloat() / 1000.0
                    ).toFloat().toString()
                }
                Log.e(
                    "查询输出电流",
                    "查询输出电流  " + maValue + "  " + mVValue + "    " + powerValue
                )
                addMessage(
                    "输出电流：${maValueRsult}mA" + "\n输出电压：${mVValueResult}V" + "\n电池电压：${
                        DecimalFormat("#.00").format((powerValue.toInt(16)).toFloat() / 1000.0)
                    }V"
                )
//                }
            }
        }
    }


}